<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Forms\RechargeForm;
use App\Modules\Recharge\RechargeRecord;
use App\Modules\Recharge\UserBalance;
use App\Modules\Shop\Shop;
use App\Modules\User\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Ramsey\Uuid\Uuid;

class RechargeController extends Controller
{

    public function index(Request $request)
    {
        $this->checkAuth('staff_recharge', 'recharge');
        $shopId = $request->input('shop_id');
        $orderId = $request->input('order_id');
        $name = $request->input('name');
        $start = $request->input('start');
        $end = $request->input('end');

        $rechargeRecords = RechargeRecord::query()
            ->where('recharge_records.shop_id', $shopId)
            ->leftJoin('shops AS s', 'recharge_records.shop_id', '=', 's.id')
            ->leftJoin('users AS u', 'recharge_records.user_id', '=', 'u.id')
            ->orderBy('recharge_records.created_at', 'desc');
        if ($orderId != '') $rechargeRecords->where('recharge_records.order_id', '=', $orderId);

        if ($name != '') {
            $rechargeRecords->where(function ($q) use ($name) {
                return $q->where('u.nickname', 'like', "%" . $name . "%")
                    ->orWhere('u.mobile', 'like', "%" . $name . "%")
                    ->orWhere('u.name', 'like', "%" . $name . "%");
            });
        }

        // if ($name != '') $rechargeRecords->where('u.nickname', 'like', '%' . $name . "%");
        if ($start != '') $rechargeRecords->where('recharge_records.created_at', '>', $start . ' 00:00:00');
        if ($end != '') $rechargeRecords->where('recharge_records.created_at', '<', $end . ' 23:59:59');

        $count = $rechargeRecords->count();
        $cz_money = $rechargeRecords->sum('recharge_records.cz_money');
        $zs_money = $rechargeRecords->sum('recharge_records.zs_money');

        $userIds = $rechargeRecords->pluck('user_id')->all();
        $userBalances = UserBalance::query()->whereIn('user_id', $userIds)->get();
        $aUserBalance = [];
        if ($userBalances) {
            foreach ($userBalances as $k => $v) {
                $aUserBalance[$v->user_id.'_'.$v->shop_id] = $v;
            }
        }

        $data = $rechargeRecords
            ->select('recharge_records.*', 'u.nickname', 'u.avatar', 'u.avatar', 's.id as shop_id', 's.name as shop_name')
            ->paginate(20)
            ->appends($request->all());

        $sidebar = 'recharge';
        return view('recharge.good_index', compact('data', 'shopId', 'sidebar', 'name', 'orderId', 'start', 'end', 'count', 'cz_money', 'zs_money', 'aUserBalance'));
    }

    public function pkgIndex(Request $request)
    {
        $this->checkAuth('staff_recharge', 'pkg_recharge');
        $shopId = $request->input('shop_id');
        $orderId = $request->input('order_id');
        $name = $request->input('name');
        $start = $request->input('start');
        $end = $request->input('end');

        $rechargeRecords = RechargeRecord::query()
            ->where('recharge_records.shop_id', $shopId)
            ->leftJoin('shops AS s', 'recharge_records.shop_id', '=', 's.id')
            ->leftJoin('users AS u', 'recharge_records.user_id', '=', 'u.id')
            ->orderBy('recharge_records.created_at', 'desc');
        if ($orderId != '') $rechargeRecords->where('recharge_records.order_id', '=', $orderId);

        if ($name != '') {
            $rechargeRecords->where(function ($q) use ($name) {
                return $q->where('u.nickname', 'like', "%" . $name . "%")
                    ->orWhere('u.mobile', 'like', "%" . $name . "%")
                    ->orWhere('u.name', 'like', "%" . $name . "%");
            });
        }

        // if ($name != '') $rechargeRecords->where('u.nickname', 'like', '%' . $name . "%");
        if ($start != '') $rechargeRecords->where('recharge_records.created_at', '>', $start . ' 00:00:00');
        if ($end != '') $rechargeRecords->where('recharge_records.created_at', '<', $end . ' 23:59:59');

        $count = $rechargeRecords->count();
        $cz_money = $rechargeRecords->sum('recharge_records.cz_money');
        $zs_money = $rechargeRecords->sum('recharge_records.zs_money');

        $userIds = $rechargeRecords->pluck('user_id')->all();
        $userBalances = UserBalance::query()->whereIn('user_id', $userIds)->get();
        $aUserBalance = [];
        if ($userBalances) {
            foreach ($userBalances as $k => $v) {
                $aUserBalance[$v->user_id.'_'.$v->shop_id] = $v;
            }
        }
        
        $data = $rechargeRecords
            ->select('recharge_records.*', 'u.nickname', 'u.avatar', 's.id as shop_id', 's.name as shop_name')
            ->paginate(20)
            ->appends($request->all());

        $category = 'recharge';
        return view('recharge.pkg_index', compact('data', 'shopId', 'category','aUserBalance', 'name', 'orderId', 'start', 'end', 'count', 'cz_money', 'zs_money'));
    }

    public function create(Request $request)
    {
        $this->checkAuth('staff_recharge_add', ['pkg_recharge_add', 'recharge_add']);

        $shopId = $request->input('shop_id');

        $shopData = Shop::query()->find($shopId);
        
        $form = $this->form(RechargeForm::class, [
            'url' => route('admin.recharge.store', ['shop_id' => $shopId]),
            'method' => 'POST',
        ]);
       
        return view('recharge.form', compact('form', 'shopId'));
    }

    public function store(Request $request)
    {
        $this->checkAuth('staff_recharge_add', ['pkg_recharge_add', 'recharge_add']);

        $shopId = $request->input('shop_id');
        $form = $this->form(RechargeForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $data = $form->getFieldValues();
        
        DB::beginTransaction();
        try {
            $data                  = $form->getFieldValues();
            //设置充值状态、充值方式、计算当前余额、生成订单号
            $data['shop_id']       = $shopId;
            $data['status']        = RechargeRecord::PAID;
            $data['recharge_mode'] = RechargeRecord::SYSTEM_RECHARGE;
            $user                  = Auth::user();
            $data['operator']      = $user->name.'('.$user->id.')';
            $data['total']         = (int)$data['cz_money']*100 + (int)$data['zs_money']*100;
            $data['order_no']      = Uuid::uuid4()->getHex();
            $data['total']         = $data['total']/100;

            RechargeRecord::query()->create($data);

            $userBalance = UserBalance::query()->where(["user_id" => $data['user_id'], "shop_id" => $data['shop_id']])->first();
            if ($userBalance) {
                UserBalance::query()
                    ->where(["user_id" => $data['user_id'], "shop_id" => $data['shop_id']])
                    ->increment("balance", $data['total']);
            } else {
                $userBalanceData = [
                    "user_id" => $data['user_id'],
                    "shop_id" => $data['shop_id'],
                    "balance" => $data['total'],
                ];
                UserBalance::query()->create($userBalanceData);
            }
            $shop = Shop::query()->find($data['shop_id']);
            $userBalance = UserBalance::query()->where(["user_id" => $data['user_id'], "shop_id" => $data['shop_id']])->first();
            $qd_user = User::query()->find($data['user_id']);
            /**
             * 临洮：充值成功
             * {{first.DATA}}
             * 充值金额：{{keyword1.DATA}}
             * 充值时间：{{keyword2.DATA}}
             * 充值门店：{{keyword3.DATA}}
             * 当前余额：{{keyword4.DATA}}
             * {{remark.DATA}}
             */
            $sendData = [
                $qd_user->openid,
                date("Y年m月d日 H时i分s秒"),
                $shop->name,
                $data['cz_money'] . "元",
                $data['zs_money'] . "元",
                $userBalance->balance . "元"
            ];
            sendMessage(35, $sendData);
            DB::commit();
        } catch (\Exception $e) {
            throw $e;
            DB::rollBack();
        }

        return redirect()->route('admin.recharge.index', ['shop_id' => $data['shop_id']]);
    }

    public function selectUser(Request $request)
    {
        $search = $request->input('term');
        $query = User::query()->limit(50);

        if (!empty($search)) {
            $query->where(function ($q) use ($search) {
                return $q->where('mobile', "like", "%".$search."%")
                    ->orWhere('name', 'like', "%".$search."%")
                    ->orWhere('nickname', 'like', "%".$search."%");
            });
        }
        
        $user = $query->get();
        $re = [];
        foreach ($user as $item) {
            $re[$item->id] = $item->nickname."（".$item->name.$item->mobile."）";
        }
        return $re;
    }

}
